package version

import (
	"regexp"
	"strings"
	"sync"
)

// PCRegMap : PreCompiled Regex Map
type PCRegMap struct {
	sync.RWMutex
	m map[string]*regexp.Regexp
}

// MustCompile : to replace regexp.MustCompile in RegFind.
func (p *PCRegMap) MustCompile(pattern string) *regexp.Regexp {
	p.RLock()
	ret, exist := p.m[pattern]
	p.RUnlock()
	if exist {
		return ret
	}
	ret = regexp.MustCompile(pattern)
	p.Lock()
	p.m[pattern] = ret
	p.Unlock()
	return ret
}

var (
	regexpCache *PCRegMap
)

func init() {
	regexpCache = new(PCRegMap)
	regexpCache.m = make(map[string]*regexp.Regexp)
}

func RegFind(pattern, subject string) []string {
	reg := regexpCache.MustCompile(pattern)
	matched := reg.FindAllStringSubmatch(subject, -1)

	if matched != nil {
		return matched[0]
	}

	return nil
}

func expandStability(stability string) string {
	stability = strings.ToLower(stability)

	switch stability {
	case "a":
		return "alpha"
	case "b":
		return "beta"
	case "p":
		return "patch"
	case "pl":
		return "patch"
	case "rc":
		return "RC"
	}

	return stability
}
